package com.example.core.tag;

import com.example.core.form.BaseForm;
import com.example.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class XForm extends BodyTagSupport {

    Logger logger = LoggerFactory.getLogger(getClass());

    public String getFormId(PageContext pageContext) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) pageContext.getRequest();
        String formName = (String) httpServletRequest.getAttribute("formName");
        if (!StringUtils.isEmpty(formName)) {
            BaseForm form = (BaseForm) httpServletRequest.getAttribute(formName);
            if (form != null) {
                return form.getFdId();
            }
        }
        return null;
    }

    @Override
    public int doStartTag() throws JspException {
        JspWriter out = pageContext.getOut();
        HttpServletRequest httpServletRequest = (HttpServletRequest) pageContext.getRequest();
        try {
            String entityName = (String) httpServletRequest.getAttribute("entityName");
            if (!StringUtils.isEmpty(entityName)) {
                out.append("<div class=\"page-context-container\">");
                out.append("<form class=\"layui-form\" action=\"/" + StringUtils.toLowerCaseFirstOne(entityName) + "/save\" method=\"post\">");
            }
            String fdId = this.getFormId(pageContext);
            if (!StringUtils.isEmpty(fdId)) {
                out.append("<input type=\"hidden\" name=\"fdId\" value=\"" + fdId + "\" />");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return EVAL_BODY_INCLUDE;
    }

    @Override
    public int doEndTag() throws JspException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) pageContext.getRequest();
        JspWriter out = pageContext.getOut();
        try {
            String entityName = (String) httpServletRequest.getAttribute("entityName");
            if (!StringUtils.isEmpty(entityName)) {
                out.print("</form>");
                out.print("</div>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return EVAL_PAGE;
    }
}
